<template>
    <WidgetContainer :widget-id="config.id">
        <FormItemWidget :config="config" :rowIndex="rowIndex" :parentId="parentId">
            <el-tree-select :class="config.attributes?.cssClass" v-model="fieldValue" :data="treeOptions" :placeholder="config.attributes.placeholder"
                :disabled="config.attributes.disabled" :size="config.attributes.size"
                :show-checkbox="config.attributes.showCheckbox" :sizcheck-strictlye="config.attributes.checkStrictly"
                :multiple="config.attributes.multiple" :style="{ width: config.attributes.width }" :props="treeProps"
                check-strictly @change="handleChange" />
        </FormItemWidget>
    </WidgetContainer>
</template>

<script setup>
import { ElTreeSelect } from 'element-plus'
import { ref, inject, onMounted } from 'vue'
import { executeEventHandler } from '@/utils/eventExecutor'
import { useFieldBinding } from '@/utils/useFieldBinding'
import { getTreeDict } from '@/api/getDict'

const props = defineProps({
    config: Object,
    rowIndex: Number,
    parentId: String
})

const formData = inject('formData')
const widgetList = inject('widgetList')
const treeOptions = ref(props.config.options || [])

const { fieldValue } = useFieldBinding(formData, props.config, {
    rowIndex: props.rowIndex,
    parentId: props.parentId
})

const treeProps = {
    label: 'label',
    children: 'children',
    value: 'value'
}

onMounted(async () => {
    executeEventHandler(props.config.events?.onMounted, {
        widgetConfig: props.config,
        formData: formData.value,
        widgetList: widgetList.value
    })

    getTreeDict(props.config)
})

const handleChange = (value) => {
    executeEventHandler(props.config.events?.onChange, {
        widgetConfig: props.config,
        formData: formData.value,
        widgetList: widgetList.value,
        value
    })
}
</script>

<style scoped>
.el-tree-select {
    width: 100%;
}
</style>